$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'promotion/promotionpolicyconfig/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', width: 30, key: true},
            {
                label: '促销方式', name: 'policyType', index: 'policy_type', width: 70, align: 'center',
                formatter: function (value, options, row) {
                    let valueText = "";
                    let policyTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').policyTypeEnum;
                    $.each(policyTypeEnum, function (index, module) {
                        if (module.value == value) {
                            valueText = module.describe;
                        }
                    });
                    return valueText;
                }
            },
            {label: '活动名称', name: 'name', index: 'name', width: 100},
            {
                label: '活动范围类型', name: 'scopeType', index: 'scope_type', width: 85, align: 'center',
                formatter: function (value, options, row) {
                    let valueText = "";
                    let scopeTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').scopeTypeEnum;
                    $.each(scopeTypeEnum, function (index, module) {
                        if (module.value == value) {
                            valueText = module.describe;
                        }
                    });
                    return valueText;
                }
            },
            {label: '店铺Id', name: 'shopId', index: 'shop_id', width: 50, align: 'center'},
            {label: '参与范围值', name: 'scopeValue', index: 'scope_value', width: 180},
            {label: '活动开始展示时间', name: 'showDate', index: 'show_date', width: 130, align: 'center'},
            {label: '活动开始时间', name: 'beginDate', index: 'begin_date', width: 130, align: 'center'},
            {label: '活动结束时间', name: 'endDate', index: 'end_date', width: 130, align: 'center'},
            {label: '优惠券有效天数', name: 'validDays', index: 'valid_days', width: 100, align: 'center'},
            {label: '延迟使用天数', name: 'delayedUseDays', index: 'delayed_use_days', width: 85, align: 'center'},
            {
                label: '特价产品是否参与优惠券', name: 'specialPartake', index: 'special_partake', width: 145, align: 'center',
                formatter: function (value, options, row) {
                    return value == true ? '参与' : '不参与';
                }
            },
            {
                label: '适用平台', name: 'purview', index: 'purview', width: 60, align: 'center',
                formatter: function (value, options, row) {
                    let valueText = "";
                    let purviewEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').purviewEnum;
                    $.each(purviewEnum, function (index, module) {
                        if (value.indexOf(module.value) != -1) {
                            valueText += module.describe + " ";
                        }
                    });
                    return valueText;
                }
            },
            {
                label: '用户类型限制', name: 'userType', index: 'user_type', width: 85, align: 'center',
                formatter: function (value, options, row) {
                    let valueText = "";
                    let userTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').userTypeEnum;
                    $.each(userTypeEnum, function (index, module) {
                        if (value.indexOf(module.value) != -1) {
                            valueText += module.describe + " ";
                        }
                    });
                    return valueText;
                }
            },
            {label: '每订单参与次数限制', name: 'orderLimitTimes', index: 'order_limit_times', width: 120, align: 'center'},
            {label: '用户参与次数限制', name: 'userLimitTimes', index: 'user_limit_times', width: 110, align: 'center'},
            {label: '总数参与次数限制', name: 'allLimitTimes', index: 'all_limit_times', width: 110, align: 'center'},
            {
                label: '优惠条件类型', name: 'conditionType', index: 'condition_type', width: 85, align: 'center',
                formatter: function (value, options, row) {
                    if (value === 'none') return '无门槛';
                    if (value === 'fullmoney') return '满钱';
                    if (value === 'fullquantity') return '满数量';
                    if (value === 'groupmustone') return '组合满一';
                }
            },
            {label: '条件参数', name: 'conditionParam', index: 'condition_param', width: 70, align: 'center'},
            {
                label: '优惠结果类型 ', name: 'resultType', index: 'result_type', width: 85, align: 'center',
                formatter: function (value, options, row) {
                    if (value === 'fullreduce') return '减钱';
                    if (value === 'franking') return '免邮';
                    if (value === 'fullgive') return '满赠';
                    if (value === 'sale') return '折扣';
                }
            },
            {label: '优惠结果参数', name: 'resultParam', index: 'result_param', width: 110, align: 'center'},
            {label: '优惠可以使用平台', name: 'stageType', index: 'stage_type', width: 110, align: 'center'},
            {label: '活动优先级', name: 'level', index: 'level', width: 80, align: 'center'},
            {label: '操作人', name: 'operation', index: 'operation', width: 80, align: 'center'},
            {label: '创建时间', name: 'createTime', index: 'create_time', width: 130, align: 'center'},
            {label: '修改时间', name: 'updateTime', index: 'update_time', width: 130, align: 'center'}
        ],
        viewrecords: true,
        height: window.innerHeight-125,
        rowNum: 20,
        rowList: [20, 50, 80],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        shrinkToFit: false,
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            // $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            vm.policyTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').policyTypeEnum;
            vm.scopeTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').scopeTypeEnum;
            vm.userTypeEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').userTypeEnum;
            vm.purviewEnum = $("#jqGrid").jqGrid('getGridParam', 'userData').purviewEnum;
        }
    });
    // 线获取添加模板基本信息
    $.get(baseURL + "goodsCategory/goodscategory/getCategoryTree", function (r) {
        vm.categoryTree = r.addInfo.categoryTree;
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        q: {
            name: '',
            policyType: ''
        },
        spuQuery: {
            goodsId: null,
            name: null,
            catId: null
        },
        spuTableData: null,
        skuTableData: null,
        goodsCategoryDialogVisible: false,
        categoryId: null, //分类id
        categoryTree: [], //商品分类树
        isAlatform: '',
        promotionPolicyConfig: {},
        policyTypeEnum: [],//促销方式枚举
        scopeTypeEnum: [],//活动范围类型枚举
        userTypeEnum: [],//用户类型枚举
        scopeValueList: [],//参与范围值List
        categoryList: [],//品类IDlist
        goodsBrandList: [],//品牌
        purviewEnum: [],//适用平台
        userTypeList: [],//限制用户类型
        skuList: [],//满赠单品List
        delobj: {  //移除的品类单品对象
            sku: '',
            category: ''
        },
        productTypes: [],
        stepMap: {},
        dialogVisible: false,
        conResult: '',//优惠结果参数
        checkeds: []
    },
    mounted() {
        //获取商品类型 品牌
        $.get(baseURL + "promotion/promotionpolicyconfig/getGoodsTypes", function (r) {
            // vm.productTypes = r.productTypes;
            vm.goodsBrandList = r.goodsBrandList;
        });
    },
    methods: {
        showDateTime: function () {
            WdatePicker({
                dateFmt: 'yyyy-MM-dd HH:mm:ss', isShowClear: false, onpicking: function (dp) {
                    vm.promotionPolicyConfig.showDate = dp.cal.getNewDateStr();
                }
            })
        },
        beginDateTime: function () {
            WdatePicker({
                dateFmt: 'yyyy-MM-dd HH:mm:ss', isShowClear: false, onpicking: function (dp) {
                    vm.promotionPolicyConfig.beginDate = dp.cal.getNewDateStr();
                }
            })
        },
        endDateTime: function () {
            WdatePicker({
                dateFmt: 'yyyy-MM-dd HH:mm:ss', isShowClear: false, onpicking: function (dp) {
                    vm.promotionPolicyConfig.endDate = dp.cal.getNewDateStr();
                }
            })
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.promotionPolicyConfig = {
                policyType: 'promotion',
                scopeType: 'sku',
                specialPartake: false,
                conditionType: 'none',
                resultType: 'fullgive',
                stageType: 0
            };
            vm.checkeds = ['pc']
            vm.userTypeList = ['common']
            vm.scopeValueList = ['']
            vm.skuList = [{}]
            vm.categoryList = ['']
            vm.isAlatform = '0',
            vm.delobj={  //移除的品类单品对象
                sku: '',
                category: ''
            }
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.skuList = [{}]
            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {

            //非空检验
            if (vm.promotionPolicyConfig.resultType != 'fullgive' && !vm.conResult) {
                alert('优惠结果参数不能为空!!!')
                return
            }
            //单品
            if (vm.promotionPolicyConfig.scopeType === 'sku' || vm.promotionPolicyConfig.scopeType === 'group') {
                vm.promotionPolicyConfig.scopeValue = vm.scopeValueList.join(',')
            }
            //品类
            if (vm.promotionPolicyConfig.scopeType === 'category') {
                vm.promotionPolicyConfig.scopeValue = vm.categoryList.join(',')
            }
            //全场
            if (vm.promotionPolicyConfig.scopeType === 'all') {
                vm.promotionPolicyConfig.scopeValue = 0
            }
            //移除的品类单品对象
            if (!vm.delobj.sku) {
                delete vm.delobj.sku;//删除属性
            }
            if (!vm.delobj.category) {
                delete vm.delobj.category;//删除属性
            }
            if (JSON.stringify(vm.delobj) != '{}') {
                vm.promotionPolicyConfig.debarScope = JSON.stringify(vm.delobj);
            } else {
                vm.promotionPolicyConfig.debarScope = ''
            }

            //用户等级阶梯限制
            if (JSON.stringify(vm.stepMap) != '{}') {
                vm.promotionPolicyConfig.userLevelLimitTimes = JSON.stringify(vm.stepMap)
            } else {
                vm.promotionPolicyConfig.userLevelLimitTimes == ''
            }

            //适用平台
            vm.promotionPolicyConfig.purview = vm.checkeds.join(",");
            //限制用户类型
            vm.promotionPolicyConfig.userType = vm.userTypeList.join(",")

            //满赠单品List
            let flag = true
            if (vm.promotionPolicyConfig.resultType == 'fullgive') {
                // vm.skuList.forEach(v => {
                //     if (!v.sku || !v.quantity) {
                //         alert('优惠结果参数不能为空!')
                //         flag = false
                //         return false
                //     }
                //     if (v.quantity <= 0) {
                //         alert('请输入正确数量!')
                //         flag = false
                //         return false
                //     }
                //     let obj = vm.productTypes.find((value, index, arr) => {
                //         return value.productId == v.sku;
                //     });
                //     if (obj) {
                //         //只能赠标品
                //         if (obj.goodsType != 'standard') {
                //             alert('只能赠送标品!')
                //             flag = false
                //             return
                //         }
                //         v.goodsType = obj.goodsType;
                //     } else {
                //         alert('赠品不存在!')
                //         flag = false
                //         return
                //     }
                // })
                // if (!flag) {
                //     return
                // }
                vm.promotionPolicyConfig.resultParam = JSON.stringify(vm.skuList);
            }

            //优惠结果参数
            if (vm.promotionPolicyConfig.resultType != 'fullgive') {
                vm.promotionPolicyConfig.resultParam = vm.conResult
            }
            //shop_id
            vm.promotionPolicyConfig.shopId = vm.isAlatform == 0 ? 1 : 0
            var url = vm.promotionPolicyConfig.id == null ? "promotion/promotionpolicyconfig/save" : "promotion/promotionpolicyconfig/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.promotionPolicyConfig),
                success: function (r) {
                    console.log(r)
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                            vm.promotionPolicyConfig.conditionParam = ''
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "promotion/promotionpolicyconfig/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            vm.scopeValueList = []
            vm.categoryList = []
            vm.stepMap = {}
            vm.delobj = {
                sku: '',
                category: ''
            }
            $.get(baseURL + "promotion/promotionpolicyconfig/info/" + id, function (r) {
                vm.promotionPolicyConfig = r.promotionPolicyConfig;
                vm.goodsBrandList = r.goodsBrandList
                //单品 组合
                if (vm.promotionPolicyConfig.scopeType === 'sku' || vm.promotionPolicyConfig.scopeType === 'group') {
                    let str = vm.promotionPolicyConfig.scopeValue
                    let arr = str.split(",")
                    vm.scopeValueList = arr
                    vm.categoryList.push([])
                }
                //品类
                if (vm.promotionPolicyConfig.scopeType === 'category') {
                    let str = vm.promotionPolicyConfig.scopeValue
                    let arr = str.split(",")
                    vm.categoryList = arr.map(function (value, index, array) {
                        return parseInt(value);
                    })
                    vm.scopeValueList.push('')
                }
                //品牌
                if (vm.promotionPolicyConfig.scopeType === 'brand') {
                    vm.categoryList.push([])
                    vm.scopeValueList.push('')
                }
                //全场
                if (vm.promotionPolicyConfig.scopeType === 'all') {
                    vm.categoryList.push([])
                    vm.scopeValueList.push('')
                }
                //使用平台
                if (vm.promotionPolicyConfig.purview) {
                    vm.checkeds = vm.promotionPolicyConfig.purview.split(",")
                }
                //用户类型
                if (vm.promotionPolicyConfig.userType) {
                    vm.userTypeList = vm.promotionPolicyConfig.userType.split(",")
                }
                //满赠单品List
                if (vm.promotionPolicyConfig.resultType == 'fullgive') {
                    vm.skuList = JSON.parse(vm.promotionPolicyConfig.resultParam)
                } else {
                    vm.conResult = vm.promotionPolicyConfig.resultParam
                }

                //移除的品类单品对象
                if (vm.promotionPolicyConfig.debarScope) {
                    vm.delobj = JSON.parse(vm.promotionPolicyConfig.debarScope)
                }
                //用户等级阶梯限制
                if (vm.promotionPolicyConfig.userLevelLimitTimes) {
                    vm.stepMap = JSON.parse(vm.promotionPolicyConfig.userLevelLimitTimes)
                }
                //是否平台券
                if (vm.promotionPolicyConfig.shopId === 0) {
                    vm.isAlatform = '1'
                } else if (vm.promotionPolicyConfig.shopId === 1) {
                    vm.isAlatform = '0'
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {//postData此数组内容直接赋值到url上，参数类型：{name1:value1…}
                    'name': vm.q.name.trim(),
                    'policyType': vm.q.policyType
                },
                page: 1
            }).trigger("reloadGrid");
        },
        reset: function () {
            vm.q.name = '';
            vm.q.policyType = '';
            vm.reload();
        },
        query: function () {
            vm.reload();
        },
        addOpt: function () {
            vm.scopeValueList.push('')
        },
        delOpt: function (index) {
            if (vm.scopeValueList.length > 1) {
                vm.scopeValueList.splice(index, 1);
            }
        },
        addcategory: function () {
            vm.categoryList.push([])
        },
        delcategory: function (index) {
            if (vm.categoryList.length > 1) {
                vm.categoryList.splice(index, 1);
            }
        },
        addsku: function () {
            vm.skuList.push({})
        },
        delsku: function (index) {
            if (vm.skuList.length > 1) {
                vm.skuList.splice(index, 1);
            }
        },


//选择sku start
        choiceCategory: function () {
            vm.goodsCategoryDialogVisible = true;
        },
        //树结构选中变化时
        categoryChange: function (value) {
            //取到末级的分类id
            vm.catId = value[value.length - 1];

           //新增功能:添加品类list
            if (vm.promotionPolicyConfig.scopeType=='category') {
                if (vm.categoryList[0] == '') {
                    vm.categoryList.splice(0,1,vm.catId)
                    return
                }
                let flag=true
                vm.categoryList.forEach(v=>{
                    if (v == vm.catId) {
                        flag=false
                        return false
                    }
                })
                if (!flag) {
                    alert('请勿重复添加')
                    return
                }
                vm.categoryList.push(vm.catId);
                return
            }

            //调用接下来的步骤
            vm.goodsCategoryDialogVisible = false;
            //加载spu数据
            vm.loadSpuData();
            // vm.spuQuery = vm.catId;
            // vm.spuGrid();
        },
        loadSpuData: function () {
            //ajax请求获得该分类下的spu列表
            // $.get(baseURL + "goods/goods/goodsList/"+catId, function(r){
            //    vm.spuTableData = r.spuTableData;
            // });
            var query = {};
            if (vm.spuQuery.goodsId != null) {
                query.goodsId = vm.spuQuery.goodsId;
            }
            if (vm.spuQuery.name != null) {
                query.name = vm.spuQuery.name;
            }
            query.category_id = vm.catId;
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goods/goodsList",
                contentType: "application/json",
                data: JSON.stringify(query),
                success: function (r) {
                    if (r.code == 0) {
                        vm.spuTableData = r.spuTableData;
                    } else {
                        alert(r.msg);
                    }
                }
            });
            vm.skuTableData = null
        },
        choiceSpu: function (row) {
            var goodsId = row.goodsId
            if (isBlank(goodsId)) {
                alert("异常信息:spu不存在,请联系管理员!")
                return;
            }
            var skuQuery = {}
            skuQuery.goods_id = goodsId;
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goodsproduct/selectProductByGoodsId",
                contentType: "application/json",
                data: JSON.stringify(skuQuery),
                success: function (r) {
                    if (r.code == 0) {
                        vm.skuTableData = r.skuTableData;
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        choiceSku: function (row) {
                if (vm.scopeValueList[0] == '') {
                    vm.scopeValueList.splice(0,1,row.productId)
                    return
                }
                let flag=true
                vm.scopeValueList.forEach(v=>{
                    if (v == row.productId) {
                        flag=false
                        return false
                    }
                })
            if (!flag) {
                alert('请勿重复添加')
                return
            }
            vm.scopeValueList.push(row.productId);
        }
//选择sku end
    }
});